package org.lee.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

/**
 * NettyByteBuf02
 *
 * @author dralee
 * @date 2022-01-03 22:56:40
 **/
public class NettyByteBuf02 {
    public static void main(String[] args) {
        // 创建ByteBuf
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello world!", CharsetUtil.UTF_8);
        // 使用相关方法
        if (byteBuf.hasArray()) {
            byte[] content = byteBuf.array();
            // 将content转成字符串
            System.out.println(new String(content, CharsetUtil.UTF_8).trim());
            System.out.println("byteBuf=" + byteBuf);
            System.out.println(byteBuf.arrayOffset()); // 0
            System.out.println(byteBuf.readerIndex()); // 0
            System.out.println(byteBuf.writerIndex()); // 12
            System.out.println(byteBuf.capacity()); // 64

            System.out.println(byteBuf.readByte()); //  读走1个字节   104(h)
            System.out.println(byteBuf.getByte(0)); //  读取第0个字节，不会改变readableBytes大小

            int len = byteBuf.readableBytes(); // 可读取字节数 12
            System.out.println("len=" + len); // 12-1 = 11

            // 使用for取出各个字节
            for (int i = 0; i < len; ++i) {
                System.out.println((char) byteBuf.getByte(i)); // 单个字母
            }

            System.out.println(byteBuf.getCharSequence(0, 4, CharsetUtil.UTF_8)); // hell
            System.out.println(byteBuf.getCharSequence(4, 6, CharsetUtil.UTF_8)); // o worl
        }
    }
}
